package com.example.officialwebsiteadmin.model.service.Impl;

import com.example.officialwebsiteadmin.model.entity.Articles;
import com.example.officialwebsiteadmin.model.entity.AuthCode;
import com.example.officialwebsiteadmin.model.mapper.ArticlesMapper;
import com.example.officialwebsiteadmin.model.service.ArticlesServices;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.*;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class ArticlesServicesImpl implements ArticlesServices {
    @Autowired
    ArticlesMapper articlesMapper;

    @Override
    public List<Articles> ArticlesList() {
        System.out.println(articlesMapper.ArticlesList());
        return articlesMapper.ArticlesList();
    }

    @Override
    public List<Articles> ArticlesPaging(Integer pagenum,Integer pagesize) {
        pagenum = pagesize * (pagenum - 1);
        List<Articles> articles = articlesMapper.ArticlesPaging(pagenum,pagesize);
        System.out.println(articles);
        for (int i = 0; i < articles.size(); i++) {
            System.out.println(i);
//            System.out.println();
        }
        return articlesMapper.ArticlesPaging(pagenum,pagesize);
    }

    @Override
    public Boolean ArticlesDel(Integer id) {
        return articlesMapper.ArticlesDel(id);
    }

    @Override
    public Boolean ArticlesPut(Object data) {
        return articlesMapper.ArticlesPut(data);
    }

    @Override
    public Boolean ArticlesAdd(Object data) {
        return articlesMapper.ArticlesAdd(data);
    }

    @Override
    public String uploadimg(MultipartFile fileUpload,String filePath) {
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID()+suffixName;
        //指定本地文件夹存储图片，写到需要保存的目录下,服务器需要写到服务器的目录
        try {
            //将图片保存到static文件夹里
            fileUpload.transferTo(new File(filePath+fileName));
            //返回提示信息
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    @Override
    public Object Code(String codeData) {
        String[] strings = codeSend(codeData);
//        String[] strings = new String[3];
//        strings[0] = "+8617860524471";
//        strings[1] = "617637";
//        strings[2] = "OK1";
        System.out.println(strings[0]);
        System.out.println(strings[1]);
        System.out.println(strings[2]);

        if (Objects.equals(strings[2], "Ok")){
            /*获取当前时间+4分钟*/
            // 获取当前时间
            LocalDateTime currentTime = LocalDateTime.now();

            // 在当前时间上加上四分钟
            LocalDateTime fourMinutesLater = currentTime.plusMinutes(4);

            // 创建时间格式化器，仅包含年、月、日、小时、分钟和秒
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            // 格式化时间为字符串
//            String formattedTime = fourMinutesLater.format(formatter);

            /*手机号存入数据库*/
            try {
                articlesMapper.ArticlesCoded(strings[0],strings[1],fourMinutesLater);
                System.out.println("存储成功");
            } catch (Exception e) {
                articlesMapper.ArticlesUpCode(strings[0],strings[1],fourMinutesLater);
                System.out.println("数据库已存在");
//                e.printStackTrace();
            }
//            List<AuthCode> authCodes = new ArrayList<>();
//            authCodes.getCode();
            String pattern = "yyyy-MM-dd HH:mm:ss"; // 日期格式

            AuthCode authCode = new AuthCode();
            authCode.setCode(strings[1]);
            authCode.setDatetime(fourMinutesLater);

            return authCode;

        }else{
            return "错误码:" + strings[2];
        }
    }

    @Override
    public Boolean subMsg(Object codeData) {
        return articlesMapper.subMsg(codeData);
    }


    public String[] codeSend(String phoneNumberSet){
        try{
            // 创建一个新的字符串数组
            String[] myArray = new String[3];

            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential("AKIDEQODxUzOcmoniPseFcu0qRnvofMvrbCa", "2oLfllaCew2viOsIVu4ziJiGBtQnyufE");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
//            String[] phoneNumberSet1 = {"+8615269095903"};
            req.setPhoneNumberSet(new String[]{phoneNumberSet});

            req.setSmsSdkAppId("1400826743");
            req.setSignName("二进制BOX公众号");
            req.setTemplateId("1945154");

            /*生成随机验证码*/
            String verificationCode = generateRandomCode(6);
            System.out.println("类型" + verificationCode.getClass().getName() + "内容是" + verificationCode);

            req.setTemplateParamSet(new String[] {verificationCode, "4"});

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            String s = SendSmsResponse.toJsonString(resp);
            System.out.println(s);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(s);
            // 获取"SendStatusSet"数组节点
            ArrayNode sendStatusSet = (ArrayNode) jsonNode.get("SendStatusSet");
            if (sendStatusSet != null && sendStatusSet.size() > 0) {
                JsonNode firstSendStatus = sendStatusSet.get(0);
                // 获取"Code"字段的值
                String codeValue = firstSendStatus.get("Code").asText();
                myArray[0] = phoneNumberSet;
                myArray[1] = verificationCode;
                myArray[2] = codeValue;
                return myArray;
            }else{
                myArray[0] = "0";
                return myArray;
            }


        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            String[] myArray = new String[1];
            myArray[0] = "0";
            return myArray;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String[] myArray = new String[1];
        myArray[0] = "0";
        return myArray;
    }


    // 生成指定长度的随机数字验证码
    public static String generateRandomCode(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("验证码长度必须大于0");
        }

        // 生成随机数
        Random random = new Random();
        StringBuilder codeBuilder = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(10); // 生成0到9之间的随机数字
            codeBuilder.append(digit);
        }

        return codeBuilder.toString();
    }

}
